package com.example.acamp.dip;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.acamp.dip.dummy.DummyContent;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class PicDetailFragment extends Fragment {

	public static final String LOG_TAG = "PicDetailFragment";
	public static final String ARG_ITEM_ID = "item_id";

	DummyContent.DummyItem mItem;

	public PicDetailFragment() {
	}

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments().containsKey(ARG_ITEM_ID)) {
			mItem = DummyContent.ITEM_MAP.get(getArguments().getString(
					ARG_ITEM_ID));
		}
		setHasOptionsMenu(true);
	}

	/* Checks if external storage is available for read and write */
	public boolean isExternalStorageWritable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	public File getFileInAlbumStorageDir(String fileName) {
		File publicDir = Environment
		.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		if ( !publicDir.exists() ) {
			publicDir.mkdirs();
		}
		File file = new File(
				publicDir,
				fileName);
		return file;
	}

	public File getFileInApplicationAlbumStorageDir(Context context, String fileName) {
		File appDir = context
		.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
		if ( !appDir.exists() ) {
			appDir.mkdirs();
		}
		File file = new File(
				appDir,
				fileName);
		return file;
	}

	@SuppressLint("NewApi")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.toggleLocation:
		{
			((PicListActivity) getActivity()).toggleSaveLocation();
			boolean externalSaveLocation = ((PicListActivity) getActivity())
					.isExternalSaveLocation();
			Toast.makeText(getActivity(), externalSaveLocation ? R.string.toast_using_gallery_storage : R.string.toast_using_application_storage, Toast.LENGTH_SHORT).show();
			if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
				getActivity().invalidateOptionsMenu();
			}
			return true;
		}
		case R.id.saveItem:
		{
			boolean externalSaveLocation = ((PicListActivity) getActivity())
					.isExternalSaveLocation();
			File file;
			if (externalSaveLocation) {
				file = getFileInAlbumStorageDir(mItem.id);
			} else {
				file = getFileInApplicationAlbumStorageDir(getActivity(), mItem.id);
			}
			CopyFileTask cft = new CopyFileTask();
			cft.execute(file.toString(), mItem.content);
			return true;
		}
		}
		return super.onOptionsItemSelected(item);
	}

	public class CopyFileTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected void onPostExecute(Boolean result) {
			Toast.makeText(getActivity(), result ? R.string.toast_file_copy_complete : R.string.toast_file_copy_failed, Toast.LENGTH_LONG).show();
			super.onPostExecute(result);
		}

		/**
		 * Called with destination, source
		 */
		@Override
		protected Boolean doInBackground(String... params) {

			String destination = params[0];
			String source = params[1];

			try {
				AssetManager am = getActivity().getAssets();
				BufferedInputStream bis = new BufferedInputStream(am.open(source));
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destination));
				byte[] buf = new byte[16384];
				int bytesRead;
				while ( -1 !=  (bytesRead = bis.read(buf) ) ) {
		            bos.write(buf, 0, bytesRead);
				}
				bis.close();
				bos.close();
				return true;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		}

	} // ListAssetsTask

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		getActivity().getMenuInflater().inflate(R.menu.detailmenu, menu);
		MenuItem saveItem = menu.findItem(R.id.saveItem);
		boolean externalSaveLocation = ((PicListActivity) getActivity())
				.isExternalSaveLocation();
		if (externalSaveLocation) {
			saveItem.setTitle(R.string.menu_save_gallery);
		} else {
			saveItem.setTitle(R.string.menu_save_app);
		}
		super.onPrepareOptionsMenu(menu);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.pic_detail, container, false);
		if (mItem != null) {

			AssetManager am = getActivity().getAssets();
			try {
				Drawable d = Drawable.createFromStream(am.open(mItem.content),
						null);
				((ImageView) rootView.findViewById(R.id.pic_detail_pic))
						.setImageDrawable(d);
			} catch (IOException e) {
				((TextView) rootView.findViewById(R.id.pic_detail))
						.setText("Could not load asset: " + mItem.content);
			}
		}
		return rootView;
	}
}
